import Vue from 'vue'
import Router from 'vue-router'
import routes from './router'
import { setTitle, getParams } from '@/libs/tools'
import { getWxOpenId } from '@/api/appoint'

Vue.use(Router)
const router = new Router({
  routes
})

router.beforeEach((to, from, next) => {
  to.meta && setTitle(to.meta.title)
  if (to.name === 'home') {
    let code = getParams('code')
    let hasToken = window.sessionStorage.getItem('openId')
    if (hasToken) {
      next()
    } else {
      if (code !== null) {
        getWxOpenId(code).then(res => {
          window.sessionStorage.setItem('token', res.data.access_token)
          window.sessionStorage.setItem('openId', res.data.openId)
          next()
        })
      } else {
        let redirectUrl = window.location.href
        redirectUrl = encodeURIComponent(redirectUrl)
        window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9f86c91e3eefbe33&redirect_uri=${redirectUrl}&response_type=code&scope=snsapi_base&state=123#wechat_redirect`
      }
    }
  } else {
    next()
  }
})

router.afterEach(to => {
  window.scrollTo(0, 0)
})

export default router
